"""
Second Life authentication backend for Django-based sites.
"""

from django.contrib.auth.models import User

from slauth.utils import valid_sl_login, get_or_create_sl_user

class SLAuthBackend:
    """
    A Second Life authentication backend for Django-based sites.
    """
    def authenticate(self, **kwargs):
        """
        Use kwargs to make the authenticate method more flexible.

        Django's admin app assumes username/password logins, so
        allow first and last in one username.  For example,
        username could be 'Bob Smith' and this method will split
        that apart into the first and last names SL login expects.

        So either of the following would work:

            >>> from django.contrib.auth import authenticate
            >>> authenticate(first_name='Bob', last_name='Smith', password='foo')
            >>> authenticate(username='Bob Smith', password='foo')
        """ 
        first_name = kwargs.get('first_name', '')
        last_name = kwargs.get('last_name', '')
        password = kwargs.get('password', '')

        if kwargs.get('username', ''):
            username = kwargs.get('username', '')
            if ' ' in username:
                first_name, last_name = username.split(' ')

        authenticated = valid_sl_login(first_name, last_name, password)

        if authenticated:
            user = get_or_create_sl_user(first_name, last_name)
            return user
        return None

    def get_user(self, user_id):
        try:
            return User.objects.get(pk=user_id)
        except User.DoesNotExist:
            return None
